import { Injectable, Logger } from '@nestjs/common';
import * as nodemailer from 'nodemailer';

@Injectable()
export class MailService {
  private readonly transporter: nodemailer.Transporter<any>;
  private readonly logger = new Logger(MailService.name);
  private readonly fromEmail: string;

  constructor() {
    // 这里建议用环境变量配置邮箱和授权码
    const host = process.env.MAIL_HOST || 'smtp.qq.com';
    const port = Number(process.env.MAIL_PORT) || 25;
    const user = process.env.MAIL_USER || '1259563100@qq.com';
    const pass = process.env.MAIL_PASS || 'dbzgpsrsfbqjijgb';

    this.fromEmail = user;

    this.transporter = nodemailer.createTransport({
      host,
      port,
      secure: port === 465, // 465端口默认使用SSL
      auth: {
        user,
        pass,
      },
    });
  }

  /**
   * 发送验证码邮件
   * @param email 收件人邮箱
   * @param code 验证码
   */
  async sendVerificationCode(email: string, code: string): Promise<boolean> {
    const mailOptions: nodemailer.SendMailOptions = {
      from: this.fromEmail,
      to: email,
      subject: '邮件验证码', // 邮件主题
      html: `<p>Your verification code is: <b>${code}</b></p>`, // 支持HTML格式
    };
    try {
      await this.transporter.sendMail(mailOptions);
      console.log(`Verification code sent to ${email}`);
      return true;
    } catch (error) {
      console.error(`Failed to send verification code to ${email}`, error);
      return false;
    }
  }
}
